<template>
  <div class="main-container">
    <!-- 日期筛选 -->
    <div class="date-filter">
      <el-button-group>
        <el-button 
          v-for="item in dateOptions" 
          :key="item.value"
          :type="activeDate === item.value ? 'primary' : ''"
          @click="handleDateChange(item.value)"
        >
          {{ item.label }}
        </el-button>
      </el-button-group>
    </div>

    <!-- 搜索筛选 -->
    <div class="search-filter">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="货品">
          <el-input 
            v-model="searchForm.goodsName" 
            placeholder="请输入货品名称/编号"
            clearable
          />
        </el-form-item>
        <el-form-item label="货品类型">
          <el-select v-model="searchForm.goodsType" placeholder="请选择" clearable>
            <el-option 
              v-for="item in goodsTypeOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单位">
          <el-select v-model="searchForm.unit" placeholder="请选择" clearable>
            <el-option 
              v-for="item in unitOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库名称">
          <el-select v-model="searchForm.warehouseName" placeholder="请选择" clearable>
            <el-option 
              v-for="item in warehouseOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="货品条码">
          <el-input 
            v-model="searchForm.barcode" 
            placeholder="请输入货品条码"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="searchForm.showDisabled">显示停用商品</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="searchForm.filterZero">过滤零库存商品</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-value blue">{{ stats.currentQuantity }}</div>
            <div class="stat-label">当前库存数量</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-value blue">{{ stats.currentAmount }}</div>
            <div class="stat-label">当前库存金额</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-value green">{{ stats.inboundQuantity }}</div>
            <div class="stat-label">入库数量</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-value orange">{{ stats.outboundQuantity }}</div>
            <div class="stat-label">出库数量</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-value green">{{ stats.pendingInbound }}</div>
            <div class="stat-label">待入库</div>
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stat-card">
            <div class="stat-value orange">{{ stats.pendingOutbound }}</div>
            <div class="stat-label">待出库</div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button @click="handleExport">导出</el-button>
      <el-button @click="handleRefresh">刷新</el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table 
        :data="tableData" 
        :loading="loading"
        @selection-change="handleSelectionChange"
        border
        stripe
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" width="80">
          <template #default="{ $index }">
            {{ (pagination.page - 1) * pagination.pageSize + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="goodsCode" label="货品编号" width="120">
          <template #default="{ row }">
            <el-link type="primary" @click="handleGoodsDetail(row)">{{ row.goodsCode }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="goodsName" label="货品名称" width="150" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === '启用' ? 'success' : 'danger'">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="goodsType" label="货品类型" width="100" />
        <el-table-column prop="specs" label="规格型号" width="120" />
        <el-table-column prop="unit" label="单位" width="80" />
        <el-table-column prop="barcode" label="条码" width="120" />
        <el-table-column prop="warehouseName" label="仓库名称" width="120" />
        <el-table-column prop="locationName" label="库位名称" width="120" />
        <el-table-column prop="currentStock" label="当前库存" width="100" />
        <el-table-column prop="stockAmount" label="库存金额" width="100" />
        <el-table-column prop="pendingInbound" label="待入库" width="100" />
        <el-table-column prop="pendingOutbound" label="待出库" width="100" />
        <el-table-column prop="availableStock" label="可用库存" width="100" />
        <el-table-column prop="availableStockAmount" label="可用库存金额" width="120" />
        <el-table-column prop="beginningStock" label="期初库存" width="100" />
        <el-table-column prop="endingStock" label="期末库存" width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-link type="success" @click="handleStockFlow(row)">出入库流水</el-link>
            <el-divider direction="vertical" />
            <el-link type="success" @click="handleStockDistribution(row)">库存分布</el-link>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup name="kccx">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useInventoryQueryApi } from '/@/api/inventory/inventoryQuery'
import { DATE_RANGE_CONFIG } from '/@/api/inventory/config'

const inventoryApi = useInventoryQueryApi()
const router = useRouter()

// 日期选项
const dateOptions = [
  { label: '今日', value: DATE_RANGE_CONFIG.TODAY },
  { label: '昨日', value: DATE_RANGE_CONFIG.YESTERDAY },
  { label: '本周', value: DATE_RANGE_CONFIG.THIS_WEEK },
  { label: '上周', value: DATE_RANGE_CONFIG.LAST_WEEK },
  { label: '本月', value: DATE_RANGE_CONFIG.THIS_MONTH },
  { label: '上月', value: DATE_RANGE_CONFIG.LAST_MONTH },
  { label: '最近半年', value: DATE_RANGE_CONFIG.LAST_HALF_YEAR },
  { label: '最近一年', value: DATE_RANGE_CONFIG.LAST_YEAR },
  { label: '自定义时间', value: DATE_RANGE_CONFIG.CUSTOM }
]

// 搜索表单
const searchForm = reactive({
  goodsName: '',
  goodsType: '',
  unit: '',
  warehouseName: '',
  barcode: '',
  showDisabled: false,
  filterZero: false
})

// 选项数据 - 动态获取
const goodsTypeOptions = ref([
  { label: '电子产品', value: '1800000000101' },
  { label: '服装鞋帽', value: '1800000000102' },
  { label: '食品饮料', value: '1800000000103' },
  { label: '家居用品', value: '1800000000104' },
  { label: '运动器材', value: '1800000000105' }
])

const unitOptions = ref<{ label: string; value: number }[]>([])
const warehouseOptions = ref<{ label: string; value: string }[]>([])

// 状态数据
const activeDate = ref(DATE_RANGE_CONFIG.TODAY)
const loading = ref(false)
const tableData = ref<any[]>([])
const selectedRows = ref<any[]>([])

// 统计数据
const stats = reactive({
  currentQuantity: 50,
  currentAmount: '500.00',
  inboundQuantity: 100,
  outboundQuantity: 100,
  pendingInbound: 100,
  pendingOutbound: 100
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 100
})

// 模拟数据
const mockData = [
  {
    goodsCode: 'G001',
    goodsName: 'iPhone 15 Pro',
    status: '启用',
    goodsType: '电子产品',
    specs: '256GB 深空黑色',
    unit: '台',
    barcode: 'G001',
    warehouseName: '主仓库',
    locationName: 'A区-01',
    currentStock: 50,
    stockAmount: 400000.00,
    pendingInbound: 20,
    pendingOutbound: 10,
    availableStock: 50,
    availableStockAmount: 400000.00,
    beginningStock: 100,
    endingStock: 50
  },
  {
    goodsCode: 'G002',
    goodsName: '运动T恤',
    status: '启用',
    goodsType: '服装鞋帽',
    specs: 'L码 蓝色',
    unit: '件',
    barcode: 'G002',
    warehouseName: '成品仓库',
    locationName: 'B区-02',
    currentStock: 200,
    stockAmount: 6000.00,
    pendingInbound: 50,
    pendingOutbound: 30,
    availableStock: 200,
    availableStockAmount: 6000.00,
    beginningStock: 300,
    endingStock: 200
  },
  {
    goodsCode: 'G003',
    goodsName: '矿泉水',
    status: '启用',
    goodsType: '食品饮料',
    specs: '500ml 纯净水',
    unit: '瓶',
    barcode: 'G003',
    warehouseName: '冷藏仓库',
    locationName: 'C区-03',
    currentStock: 1000,
    stockAmount: 2000.00,
    pendingInbound: 200,
    pendingOutbound: 150,
    availableStock: 1000,
    availableStockAmount: 2000.00,
    beginningStock: 1500,
    endingStock: 1000
  },
  {
    goodsCode: 'G004',
    goodsName: '跑步机',
    status: '启用',
    goodsType: '运动器材',
    specs: '家用电动跑步机',
    unit: '台',
    barcode: 'G004',
    warehouseName: '原料仓库',
    locationName: 'D区-04',
    currentStock: 15,
    stockAmount: 45000.00,
    pendingInbound: 5,
    pendingOutbound: 3,
    availableStock: 15,
    availableStockAmount: 45000.00,
    beginningStock: 25,
    endingStock: 15
  },
  {
    goodsCode: 'HPDH9012',
    goodsName: '洗衣机',
    status: '启用',
    goodsType: '化妆品',
    specs: 'blue 蓝色的',
    unit: '卷',
    barcode: '000005454de',
    warehouseName: '仓库一',
    locationName: '仓位一',
    currentStock: 50,
    stockAmount: 500.00,
    pendingInbound: 18,
    pendingOutbound: 7,
    availableStock: 50,
    availableStockAmount: 500.00,
    beginningStock: 75,
    endingStock: 50
  },
  {
    goodsCode: 'HPDH4022',
    goodsName: '电脑',
    status: '停用',
    goodsType: '鞋类',
    specs: 'blue 蓝色的',
    unit: '斤',
    barcode: '000005454de',
    warehouseName: '仓库一',
    locationName: '仓位一',
    currentStock: 50,
    stockAmount: 500.00,
    pendingInbound: 0,
    pendingOutbound: 0,
    availableStock: 50,
    availableStockAmount: 500.00,
    beginningStock: 60,
    endingStock: 50
  },
  {
    goodsCode: 'HPDH3456',
    goodsName: '手表',
    status: '启用',
    goodsType: '配饰',
    specs: 'blue 蓝色的',
    unit: '件',
    barcode: '000005454de',
    warehouseName: '仓库一',
    locationName: '仓位一',
    currentStock: 50,
    stockAmount: '500.00'
  },
  {
    goodsCode: 'HPDH7890',
    goodsName: '钢笔',
    status: '启用',
    goodsType: '玩具',
    specs: 'blue 蓝色的',
    unit: '盒',
    barcode: '000005454de',
    warehouseName: '仓库一',
    locationName: '仓位一',
    currentStock: 50,
    stockAmount: '500.00'
  },
  {
    goodsCode: 'HPDH2345',
    goodsName: '餐具套装',
    status: '启用',
    goodsType: '书籍',
    specs: 'blue 蓝色的',
    unit: '瓶',
    barcode: '000005454de',
    warehouseName: '仓库一',
    locationName: '仓位一',
    currentStock: 50,
    stockAmount: '500.00'
  },
  {
    goodsCode: 'HPDH6789',
    goodsName: '运动鞋',
    status: '启用',
    goodsType: '运动器材',
    specs: 'blue 蓝色的',
    unit: '粒',
    barcode: '000005454de',
    warehouseName: '仓库一',
    locationName: '仓位一',
    currentStock: 50,
    stockAmount: '500.00'
  }
]

// 页面加载
onMounted(() => {
  loadData()
  loadStats()
  loadDropdownData()
})

// 加载下拉选项数据
const loadDropdownData = async () => {
  try {
    // 加载单位选项
    const unitResult = await inventoryApi.getUnits()
    if (unitResult.data && unitResult.data.result) {
      unitOptions.value = unitResult.data.result.map((item: any) => ({
        label: item.label || item.name,
        value: item.value || item.id
      }))
    } else {
      // 如果API调用失败，使用默认数据
      unitOptions.value = [
        { label: '台', value: 1 },
        { label: '个', value: 2 },
        { label: '件', value: 3 },
        { label: '箱', value: 4 },
        { label: '包', value: 5 },
        { label: '瓶', value: 6 },
        { label: '盒', value: 7 },
        { label: '套', value: 8 },
        { label: '袋', value: 9 },
        { label: '公斤', value: 10 }
      ]
    }
    
    // 加载仓库选项
    const warehouseResult = await inventoryApi.getWarehouses()
    if (warehouseResult.data && warehouseResult.data.result) {
      warehouseOptions.value = warehouseResult.data.result.map((item: any) => ({
        label: item.wareName || item.name,
        value: item.id
      }))
    } else {
      // 如果API调用失败，使用默认数据
      warehouseOptions.value = [
        { label: '主仓库', value: '主仓库' },
        { label: '成品仓库', value: '成品仓库' },
        { label: '原料仓库', value: '原料仓库' },
        { label: '临时仓库', value: '临时仓库' },
        { label: '冷藏仓库', value: '冷藏仓库' }
      ]
    }
    
    console.log('下拉选项数据加载完成')
  } catch (error) {
    console.error('加载下拉选项数据失败:', error)
    ElMessage.warning('加载选项数据失败，使用默认数据')
    // 使用默认数据作为备选
    unitOptions.value = [
      { label: '台', value: 1 },
      { label: '个', value: 2 },
      { label: '件', value: 3 },
      { label: '箱', value: 4 },
      { label: '包', value: 5 },
      { label: '瓶', value: 6 },
      { label: '盒', value: 7 },
      { label: '套', value: 8 },
      { label: '袋', value: 9 },
      { label: '公斤', value: 10 }
    ]
    warehouseOptions.value = [
      { label: '主仓库', value: '主仓库' },
      { label: '成品仓库', value: '成品仓库' },
      { label: '原料仓库', value: '原料仓库' },
      { label: '临时仓库', value: '临时仓库' },
      { label: '冷藏仓库', value: '冷藏仓库' }
    ]
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    const result = await inventoryApi.getStats({
      warehouseName: searchForm.warehouseName,
      dateRange: getDateRange()
    })
    
    if (result.data && result.data.result) {
      Object.assign(stats, result.data.result)
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    // 使用默认统计数据
  }
}

// 获取日期范围
const getDateRange = () => {
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  
  switch (activeDate.value) {
    case DATE_RANGE_CONFIG.TODAY:
      return [today, new Date(today.getTime() + 24 * 60 * 60 * 1000 - 1)]
    case DATE_RANGE_CONFIG.YESTERDAY:
      const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)
      return [yesterday, new Date(yesterday.getTime() + 24 * 60 * 60 * 1000 - 1)]
    case DATE_RANGE_CONFIG.THIS_WEEK:
      const startOfWeek = new Date(today)
      startOfWeek.setDate(today.getDate() - today.getDay())
      return [startOfWeek, new Date(today.getTime() + 24 * 60 * 60 * 1000 - 1)]
    case DATE_RANGE_CONFIG.LAST_WEEK:
      const lastWeekStart = new Date(today)
      lastWeekStart.setDate(today.getDate() - today.getDay() - 7)
      const lastWeekEnd = new Date(lastWeekStart.getTime() + 7 * 24 * 60 * 60 * 1000 - 1)
      return [lastWeekStart, lastWeekEnd]
    case DATE_RANGE_CONFIG.THIS_MONTH:
      const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
      return [startOfMonth, new Date(today.getTime() + 24 * 60 * 60 * 1000 - 1)]
    case DATE_RANGE_CONFIG.LAST_MONTH:
      const lastMonthStart = new Date(now.getFullYear(), now.getMonth() - 1, 1)
      const lastMonthEnd = new Date(now.getFullYear(), now.getMonth(), 0, 23, 59, 59)
      return [lastMonthStart, lastMonthEnd]
    case DATE_RANGE_CONFIG.LAST_HALF_YEAR:
      const halfYearAgo = new Date(now.getTime() - 6 * 30 * 24 * 60 * 60 * 1000)
      return [halfYearAgo, new Date(today.getTime() + 24 * 60 * 60 * 1000 - 1)]
    case DATE_RANGE_CONFIG.LAST_YEAR:
      const yearAgo = new Date(now.getTime() - 365 * 24 * 60 * 60 * 1000)
      return [yearAgo, new Date(today.getTime() + 24 * 60 * 60 * 1000 - 1)]
    default:
      return null
  }
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 调用后端API
    const result = await inventoryApi.page({
      ...searchForm,
      page: pagination.page,
      pageSize: pagination.pageSize
    })
    
    if (result.data && result.data.result) {
      tableData.value = result.data.result.items || []
      pagination.total = result.data.result.total || 0
    } else {
      // 如果API调用失败，使用模拟数据
      tableData.value = mockData
      pagination.total = 100
    }
  } catch (error) {
    console.error('API调用失败:', error)
    ElMessage.error('加载数据失败，使用模拟数据')
    // 使用模拟数据作为备选
    tableData.value = mockData
    pagination.total = 100
  } finally {
    loading.value = false
  }
}

// 日期变化
const handleDateChange = (value: string) => {
  activeDate.value = value
  loadData()
  loadStats()
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadData()
  loadStats()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    goodsName: '',
    goodsType: '',
    unit: '',
    warehouseName: '',
    barcode: '',
    showDisabled: false,
    filterZero: false
  })
  loadData()
  loadStats()
}

// 刷新
const handleRefresh = () => {
  loadData()
  loadStats()
}

// 导出
const handleExport = async () => {
  try {
    const result = await inventoryApi.exportData({
      ...searchForm,
      page: pagination.page,
      pageSize: pagination.pageSize
    })
    
    // 创建下载链接
    const blob = new Blob([result.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `库存查询_${new Date().toISOString().slice(0, 10)}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  loadData()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadData()
}

// 货品详情
const handleGoodsDetail = (row: any) => {
  ElMessage.info(`查看货品详情: ${row.goodsName}`)
}

// 出入库流水
const handleStockFlow = async (row: any) => {
  try {
    // 跳转到流水页面，只传递货品编号参数
    router.push({
      path: '/kc/ls',
      query: {
        goodsCode: row.goodsCode
      }
    })
  } catch (error) {
    console.error('跳转流水页面失败:', error)
    ElMessage.error('跳转流水页面失败')
  }
}

// 库存分布
const handleStockDistribution = async (row: any) => {
  try {
    // 跳转到库存分布页面，传递货品编号参数
    router.push({
      path: '/kc/kcfb',
      query: {
        goodsCode: row.goodsCode,
        goodsName: row.goodsName,
        warehouseName: row.warehouseName
      }
    })
  } catch (error) {
    console.error('跳转库存分布页面失败:', error)
    ElMessage.error('跳转库存分布页面失败')
  }
}
</script>

<style scoped>
.main-container {
  padding: 20px;
}

.date-filter {
  margin-bottom: 20px;
}

.search-filter {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  margin: 0;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-value.blue {
  color: #409eff;
}

.stat-value.green {
  color: #67c23a;
}

.stat-value.orange {
  color: #e6a23c;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.action-buttons {
  margin-bottom: 20px;
}

.table-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
